package com.itheima.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.mapper.UmsRoleResourceRelationMapper;
import com.itheima.pojo.UmsRoleResourceRelation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class UmsRoleResourceRelationImpl implements UmsRoleResourceRelationApi {

    @Autowired
    private UmsRoleResourceRelationMapper mapper;

    /**
     * 给角色分配资源
     */
    @Override
    public void allocResource(Integer roleId, ArrayList<Integer> resourceIds) {

        LambdaQueryWrapper<UmsRoleResourceRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsRoleResourceRelation::getRoleId, roleId);
        List<UmsRoleResourceRelation> umsRoleResourceRelations = mapper.selectList(lqw);

        //1.首先判断传入的menuIds是否为空
        if (resourceIds.size() == 0) {
            //如果为空,查询数据库是否有数据
            if (umsRoleResourceRelations.size() == 0) {
                //数据库也没有数据的话直接结束;
                return;

            } else {
                //如果数据库有数据,将数据库的数据清除
                mapper.delete(lqw);
            }
            //2.如果传入的ids不为空,查看数据库是否有数据
        } else {

            if (umsRoleResourceRelations.size() == 0) {
                //数据库没有数据的话直接保存;
                for (Integer resourceId : resourceIds) {
                    UmsRoleResourceRelation rrr = new UmsRoleResourceRelation();
                    rrr.setResourceId(Long.valueOf(resourceId));
                    rrr.setRoleId(Long.valueOf(roleId));
                    mapper.insert(rrr);
                }
            } else {
                //如果数据库有数据,将数据库的数据原来的数据清除保存新的数据
                mapper.delete(lqw);

                for (Integer resourceId : resourceIds) {
                    UmsRoleResourceRelation rrr = new UmsRoleResourceRelation();
                    rrr.setResourceId(Long.valueOf(resourceId));
                    rrr.setRoleId(Long.valueOf(roleId));
                    mapper.insert(rrr);
                }
            }
        }
    }

    /**
     * 获取资源相关资源列表
     */
    @Override
    public List<UmsRoleResourceRelation> listRrr(Integer roleId) {
        LambdaQueryWrapper<UmsRoleResourceRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsRoleResourceRelation::getRoleId,roleId);
        List<UmsRoleResourceRelation> umsRoleResourceRelations = mapper.selectList(lqw);
        return umsRoleResourceRelations;
    }


}
